/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(['N/record', 'N/render', 'N/file'], function (record, render, file) {
    function beforeLoad(context) {
        if (context.type === 'view') {
            try {
                var wo = record.load({
                    type: 'workorder',
                    id: context.newRecord.id,
                    isDynamic: true
                });
                var label = {};

                label.tranid = wo.getValue('tranid'); //工单编号
                var manufacturingroutingId = wo.getValue('manufacturingrouting');//工序流程
                var manuRec = record.load({
                    type: record.Type.MANUFACTURING_ROUTING,
                    id: manufacturingroutingId,
                    isDynamic: true
                });
                //工序流程数
                var steps = [];
                var count = manuRec.getLineCount('routingstep');
                for (var i = 0; i < count; i++) {
                    var step = {};
                    manuRec.selectLine({sublistId: 'routingstep', line: i});
                    step.operationsequence = manuRec.getCurrentSublistText('routingstep','operationsequence');
                    step.operationname = manuRec.getCurrentSublistText( 'routingstep', 'operationname');
                    step.barcode = '0000000000' + step.operationsequence;//条形码
                    //工序
                    steps[i] = step;
                }
                label.steps = steps;
                //调用模板文件
                var renderer = render.create();
                renderer.templateContent = file.load(581).getContents();
                renderer.addCustomDataSource({
                    format: render.DataSource.JSON,
                    alias: 'label',
                    data: JSON.stringify(label)
                });
                var pdfFile = renderer.renderAsPdf();
                //PDF文件存放文件夹ID
                pdfFile.folder = 185;
                pdfFile.name = label.tranid +new Date().getTime()+ '.pdf';
                var fileId = pdfFile.save();
                var File = file.load(fileId);
                var pdfurl = File.url;
                var form = context.form;
                form.addButton({
                    id: 'custpage_button',
                    label: '打印工序号',
                    functionName: "window.open('" + pdfurl + "');"
                });
            } catch (e) {
                log.error(e.name, e.message);
            }

        }
    }

    return {
        beforeLoad: beforeLoad
    };
});
